<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://hyperf.wiki
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Controller\Admin\Sys;

use App\Controller\AbstractController;
use App\Middleware\AuthMiddleware;
use App\Model\Moment;
use Hyperf\Context\Context;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\DeleteMapping;
use Hyperf\HttpServer\Annotation\GetMapping;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\PutMapping;
use Hyperf\HttpServer\Annotation\RequestMapping;

#[Middlewares([AuthMiddleware::class])]
#[Controller]
class MomentController extends AbstractController
{
    #[GetMapping(path: '/sys/moment/list')]
    public function list()
    {
        $pageNum = $this->request->input('pageNum', 1);
        $pageSize = $this->request->input('pageSize', 10);

        $list = Moment::query()
            ->select('id', 'user_id','content', 'images', 'create_time as createTime', 'update_time as updateTime')
            ->forPage($pageNum, $pageSize)->get();
        $data['searchCount'] = true;
        $data['current'] = (int)$pageNum;
        $data['size'] = (int)$pageSize;
        $data['total'] = Moment::query()->count();
        $data['pages'] = ceil($data['total'] / $pageSize);
        $data['records'] = $list;
        return success($data);
    }

    #[RequestMapping(path: '/sys/moment/add',methods: ['POST'])]
    public function add()
    {
        $params = $this->request->all();
        $params['user_id'] = Context::get('uid');
        Moment::query()->create($params);
        return success();
    }

    #[PutMapping(path: '/sys/moment/update')]
    public function update()
    {
        $params = $this->request->all();
        Moment::query()->where('id', $params['id'])->update([
            'content' => $params['content'],
            'images' => $params['images']
        ]);
        return success();
    }

    #[DeleteMapping(path: '/sys/moment/delete/{ids}')]
    public function delete($ids)
    {
        try {
            $idArr = explode(',', $ids);
            foreach ($idArr as $id) {
                $moment = Moment::query()->where('id', $id)->first();
                if ($moment) {
                    Moment::query()->where('id', $id)->delete();
                }
            }
            return success();
        } catch (\Throwable $e) {
            logInfo('delete', $e->getMessage(), 'category');
        }

    }
}
